import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/mysql';
import { verifyToken } from '@/lib/auth';
import { QUESTION_BANK } from '@questions';

// 获取检测统计
export async function GET(request: NextRequest) {
  try {
    // 验证管理员权限
    const token = request.cookies.get('token')?.value;
    if (!token) {
      return NextResponse.json({ error: '未登录' }, { status: 401 });
    }

    const payload = verifyToken(token);
    if (!payload || payload.role !== 'admin') {
      return NextResponse.json({ error: '无权限' }, { status: 403 });
    }

    const userId = payload.userId;

    // 计算总题目数
    let totalQuestions = 0;
    const topicStats: any = {};

    for (const [topic, questions] of Object.entries(QUESTION_BANK)) {
      totalQuestions += questions.length;
      topicStats[topic] = {
        topicId: topic,
        topicName: topic,
        total: questions.length,
        reviewed: 0,
        correct: 0,
        marked: 0,
        skipped: 0
      };
    }

    // 获取整体统计
    const overallStatsResult = await db.query(
      `SELECT 
        COUNT(*) as total_reviewed,
        SUM(CASE WHEN status = 'correct' THEN 1 ELSE 0 END) as correct_count,
        SUM(CASE WHEN status = 'incorrect' THEN 1 ELSE 0 END) as incorrect_count,
        SUM(CASE WHEN status = 'marked' THEN 1 ELSE 0 END) as marked_count,
        SUM(CASE WHEN status = 'skipped' THEN 1 ELSE 0 END) as skipped_count
       FROM question_reviews
       WHERE reviewed_by = ? AND status != 'pending'`,
      [userId]
    ) as any;

    const overallStats = Array.isArray(overallStatsResult) ? overallStatsResult : [];

    // 获取按知识点统计
    const topicReviewsResult = await db.query(
      `SELECT 
        topic_id,
        COUNT(*) as reviewed,
        SUM(CASE WHEN status = 'correct' THEN 1 ELSE 0 END) as correct,
        SUM(CASE WHEN status = 'marked' THEN 1 ELSE 0 END) as marked,
        SUM(CASE WHEN status = 'skipped' THEN 1 ELSE 0 END) as skipped
       FROM question_reviews
       WHERE reviewed_by = ? AND status != 'pending'
       GROUP BY topic_id`,
      [userId]
    ) as any;

    const topicReviews = Array.isArray(topicReviewsResult) ? topicReviewsResult : [];

    // 合并知识点统计
    topicReviews.forEach((tr: any) => {
      if (topicStats[tr.topic_id]) {
        topicStats[tr.topic_id].reviewed = tr.reviewed;
        topicStats[tr.topic_id].correct = tr.correct;
        topicStats[tr.topic_id].marked = tr.marked;
        topicStats[tr.topic_id].skipped = tr.skipped;
      }
    });

    // 获取问题题目列表
    const problemQuestionsResult = await db.query(
      `SELECT question_id, topic_id, topic_name, question_index, status, issue_type, notes, reviewed_at
       FROM question_reviews
       WHERE reviewed_by = ? AND status IN ('incorrect', 'marked')
       ORDER BY reviewed_at DESC`,
      [userId]
    ) as any;

    const problemQuestions = Array.isArray(problemQuestionsResult) ? problemQuestionsResult : [];
    const stats = overallStats[0] || {};

    return NextResponse.json({
      overall: {
        total: totalQuestions,
        reviewed: Number(stats.total_reviewed) || 0,
        correct: Number(stats.correct_count) || 0,
        incorrect: Number(stats.incorrect_count) || 0,
        marked: Number(stats.marked_count) || 0,
        skipped: Number(stats.skipped_count) || 0,
        remaining: totalQuestions - (Number(stats.correct_count) || 0),
        progress: totalQuestions > 0 ? ((Number(stats.correct_count) || 0) / totalQuestions * 100).toFixed(2) : 0
      },
      byTopic: Object.values(topicStats),
      problems: problemQuestions
    });

  } catch (error: any) {
    console.error('获取统计失败:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

